#include "file_util.h"
#include <vector>
#include <dirent.h>
#include <iostream>
#include <list>
#include <sstream>
#include <math.h>
#include <fstream>
using namespace std;

file_util::file_util()
{
}
bool file_util::copyFile( char * src,  char * des)
{
    char * buffer;
      long size;
      ifstream infile (src,ifstream::binary);
      ofstream outfile (des,ofstream::binary);

      // get size of file
      infile.seekg(0,ifstream::end);
      size=infile.tellg();
      infile.seekg(0);

      // allocate memory for file content
      buffer = new char [size];

      // read content of infile
      infile.read (buffer,size);

      // write to outfile
      outfile.write (buffer,size);

      // release dynamically-allocated memory
      delete[] buffer;

      outfile.close();
      infile.close();
      return 0;
}

vector<string> file_util::listDirectory(string dir){
    DIR *dp;
    vector<string> files;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error opening " << dir << endl;
        return files;
    }

    while ((dirp = readdir(dp)) != NULL) {
        if(string(dirp->d_name) == ".") continue;
        if(string(dirp->d_name) == "..") continue;
        files.push_back(dirp->d_name);
    }
    closedir(dp);
    return files;
}

std::vector<std::string> file_util::split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    while(std::getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}


std::vector<std::string> file_util::split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

vector<string> file_util::decompose_file_name(string filename, char token){
    vector<string> tokens;
    if(filename.find(token) != string::npos){
        tokens = file_util::split(filename,token);
    }
    return tokens;
}

string file_util::getFileExtension(string fileName)
{
    int pos = fileName.find_last_of('.');
    if (pos == -1)
        return NULL;
    return fileName.substr(pos + 1);
}
